import React, { useState, useMemo, useEffect } from 'react';
import { ColView, filter_list, useHigh, GridTable, filter_row, useCmd, WaitUmd, MainView, no_del, trim_data, KFile, HandView, BtTxt,
    cline, uJob, Title, obj_int, obj_str, PanelFind, Btn, is_empty, loc } from 'sui';
import { useAccess } from 'cache';
import { get_col, load_supply, fix_col, get_ck, load_col } from '../cmd';
import { DlgNum } from '../ctl';
import { TraceView } from '../trace';
import { Census } from './census';
import { User } from 'cache';

const SimpleView = ({ mod, title, acc }) => {
    const [open_val, openVal] = useState(false);
    const [supply, setSupply] = useState();
    const [map_supply, mapSupply] = useState();
    const [col, setCol] = useState();
    const [high] = useHigh(140, 100);
    const [no_acc] = useAccess();
    const umd = useCmd(`${mod}/list`);

    useEffect(() => {
        load_col(mod, setCol);
        load_supply(mod, setSupply, mapSupply);
    }, [mod]);

    const getRow = useMemo(() => {
        const lst = filter_list(["sn"], col);
        return filter_row(umd.value, lst, umd.filter);
    }, [umd.value, umd.filter, col]);

    const hreturn = () => {
        load_col(mod, setCol);
        umd.hreturn();
    };

    const calc_v = (v) => {
        const dnum = obj_int(v, "dnum");
        const bnum = obj_int(v, "bnum");
        v["num"] = dnum + bnum;

        return v;
    };

    const pact = {
        "pick": v => openVal(true),
        "out": v => openVal(true),
    };

    const hModify = (opt, v) => {
        umd.startWait();

        const cmd = {
            line: cline(),
            sn: obj_str(umd.cur, "sn"),
            num: obj_int(v, "dnum"),
            opt: opt,
            tp: mod,
            uname: User.uName(),
        };

        if (mod === "forge" && opt === "out") {
            cmd["tech"] = obj_str(v, "tech");
            cmd["std"] = obj_str(v, "std");
        }

        uJob(null, "stock/change", cmd, r => umd.reload(umd.endWait), e => umd.setErr());
    };

    const act = {
        "add": (v, h) => umd.update(`${mod}/add`, {"v": calc_v(v)}, h),
        "edit": (v, h) => umd.update(`${mod}/md`, {"v": [calc_v(v)]}, h),
        "pick": (v) => hModify("pick", v),
        "out": (v) => hModify("out", v),
    };

    if (umd.isFin("col")) {
        const list = [
            {sn: mod, name: title, fix: fix_col()},
            {sn: `stock${mod}`, name: loc("l_112")},
        ];

        return <ColView hreturn={hreturn} title={title} subtitle={loc("l_221")} list={list} cur={mod}/>;
    }

    if (umd.isFin("trace")) {
        return <TraceView hreturn={umd.hreturn} title={title} mod={mod}/>;
    }

    const hDel = (d) => {
        if (no_del()) {
            return;
        }

        umd.update(`${mod}/rm`, {"k": obj_str(d, "sn")});
    };

    const hCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const ret = [];

        col.forEach(d => {
            if (d.sn === "tmget" || d.sn === "tmin") {
                d.ctp = "datetime";
            } else if (d.sn === "supply") {
                d.ctp = "list";
                d.ctl = supply;
            }

            ret.push(d);
        });

        return ret;
    };

    if (umd.isFin("edit") || umd.isFin("add")) {
        return <HandView umd={umd} title={title} act={act} col={hCol()} ck={get_ck(umd.cur, umd.value, col)}/>;
    }

    if (umd.isFin("census")) {
        return <Census hreturn={() => umd.hreturn()} data={umd.value} col={col} title={title}/>;
    }

    const hImport = (val) => {
        if (is_empty(col)) {
            alert(loc("l_686"));
            return;
        }

        if (is_empty(val)) {
            alert(loc("l_276"));
            return;
        }

        trim_data(val, ["sn"]);

        umd.update(`${mod}/madd`, {v: val});
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_238"), key: 'e_opt', width: 320, frozen: true, formatter: props => {
                const d = props.row;

                let pre = loc("l_141");
                if (mod === "forge") {
                    pre = loc("l_142");
                }

                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => umd.pact(pact, d, "pick")} disabled={no_acc(acc + "b")}>{`${pre}${loc("l_741")}`}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(pact, d, "out")} disabled={no_acc(acc + "b")}>{`${pre}${loc("l_139")}`}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(null, d, "edit")} disabled={no_acc(acc + "a")}>{loc("l_235")}</BtTxt>
                        <BtTxt hcmd={() => hDel(d)} disabled={no_acc(acc + "a")}>{loc("l_237")}</BtTxt>
                    </div>
                );
            }},
        ];

        get_col(col, tmp, map_supply);

        return tmp;
    };

    const getList = () => {
        if (is_empty(col)) {
            return null;
        }

        return col.map(d => d.sn);
    };

    const rowTempl = () => {
        const tmp = getList();
        if (is_empty(tmp)) {
            return null;
        }

        const v = {};
        tmp.forEach(k => v[k] = "1");

        return [v];
    };

    const Right = () => (
        <div className="flex items-center">
            <div className="flex items-center mr-4">
                <Btn color="teal" hcmd={() => umd.pact(null, null, "trace")}>{loc("l_112")}</Btn>
                <Btn className="mx-4" hcmd={() => umd.pact(null, null, "col")} disabled={no_acc(acc + "a")}>{loc("l_221")}</Btn>
                <KFile umd={umd} title={title} col={getList()} row={rowTempl()} hcmd={hImport} no_acc_in={no_acc(acc + "a")}/>
                <Btn color="green" hcmd={() => umd.pact(null, null, "add")} className="ml-3" disabled={no_acc(acc + "a")}>{loc("l_239")}</Btn>
            </div>
        </div>
    );

    const Left = () => (
        <div className="inline-flex items-center">
            <Title mod={title} sub={loc("l_323")}/>
            <Btn className="ml-8" hcmd={() => umd.pact(null, null, "census")} color="teal">{loc("l_115")}</Btn>
        </div>
    );

    return (
        <MainView>
            <PanelFind left={<Left/>} right={<Right/>} hcmd={v => umd.setFilter(v)}/>
            <GridTable col={getCol()} row={getRow} high={high} gref={umd.gref}/>
            <DlgNum open={open_val} hcmd={v => umd.act(act, v)} setOpen={openVal} data={umd.cur} fin={umd.fin} col={col} mod={mod}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {SimpleView};
